package com.net.user.controller;

import com.caikun.model.common.Result;
import com.caikun.model.dto.UserLoginDTO;
import com.caikun.model.dto.UserRegisterDTO;
import com.caikun.model.entity.User;
import com.caikun.model.utils.JwtUtils;
import com.caikun.model.vo.UserLoginVO;
import com.net.user.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     * @param userLoginDTO
     * @return
     */
    @PostMapping("/login")
    @Operation(summary = "用户登录")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) throws Exception {
        log.info("用户登录：{}", userLoginDTO);

        User user = userService.login(userLoginDTO);
        if (user == null) {
            return Result.fail("用户名或密码错误");
        }
        // 生成JWT Token
        // token携带信息
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", user.getUserId());
        claims.put("username", user.getUsername());
        String token = JwtUtils.generateToken(user.getRealName(), claims);

        UserLoginVO data = UserLoginVO.builder()
                .username(user.getUsername())
                .token(token)
                .userId(user.getUserId())
                .menus(userService.getUserMenus(user.getUserId()))
                .build();

        return Result.success(data);
    }

    /**
     * 用户注册
     * @param userRegisterDTO
     * @return
     */
    @PostMapping("/register")
    @Operation(summary = "用户注册")
    public Result<String> register(@RequestBody UserRegisterDTO userRegisterDTO) {
        log.info("用户注册：{}", userRegisterDTO);
        try {
            boolean success = userService.register(userRegisterDTO);
            if (success) {
                User user = userService.getUserByUsername(userRegisterDTO.getUsername());
                return Result.success("注册成功");
            } else {
                return Result.fail("注册失败");
            }
        } catch (Exception e) {
            log.error("用户注册异常：", e);
            return Result.fail("注册失败：" + e.getMessage());
        }
    }


    /**
     * 根据用户ID查询用户信息
     * @param userId 用户ID
     * @return 用户信息
     */
    @GetMapping("/info/{userId}")
    @Operation(summary = "根据用户ID查询用户信息")
    public Result<User> getUserInfo(@PathVariable Long userId) {
        User user = userService.getUserById(userId);
        if (user != null) {
            return Result.success(user);
        } else {
            return Result.fail("用户不存在");
        }
    }

    /**
     * 验证用户权限
     * @param userId 用户ID
     * @param requireUserPermission 需要的用户权限
     * @return 是否有权限
     */
    @GetMapping("/permission/{userId}/{requireUserPermission}")
    @Operation(summary = "验证用户权限")
    public Result<Boolean> checkPermission(@PathVariable Long userId, @PathVariable Integer requireUserPermission) {
        log.info("验证用户权限：userId={}, requireUserPermission={}", userId, requireUserPermission);
        boolean hasPermission = userService.hasPermission(userId, requireUserPermission);
        return Result.success(hasPermission);
    }

    /**
     * 条件查询用户列表
     * @param user 查询条件
     * @return 用户列表
     */
    @PostMapping("/queryByCondition")
    @Operation(summary = "条件查询用户列表")
    public Result<List<User>> queryByCondition(@RequestBody User user) {
        log.info("条件查询用户列表：{}", user);
        List<User> users = userService.queryByCondition(user);
        return Result.success(users);
    }

    /**
     * 更新用户信息
     * @param user 用户信息
     * @return 是否更新成功
     */
    @PostMapping("/edit")
    @Operation(summary = "更新用户信息")
    public Result<Boolean> updateUser(@RequestBody User user) {
        log.info("更新用户信息：{}", user);
        boolean success = userService.updateUser(user);
        return Result.success(success);
    }

    /**
     * 删除用户
     * @param userId 用户ID
     * @return 是否删除成功
     */
    @DeleteMapping("/delete/{userId}")
    @Operation(summary = "删除用户")
    public Result<Boolean> deleteUser(@PathVariable Long userId) {
        log.info("删除用户：{}", userId);
        boolean success = userService.deleteUser(userId);
        return Result.success(success);
    }
}
